package com.share.base.filter;

import com.share.base.utils.JWTUtil;
import com.share.base.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class SecurityFilter extends HttpFilter {
    private static final Logger logger = LoggerFactory.getLogger(SecurityFilter.class); // 日志记录器

    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            String uri = request.getRequestURI();
            logger.trace("Request URI: {}", uri);

            if (isExcluded(uri)) {
                chain.doFilter(request, response);
                return;
            }

            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                logger.error("Token为空");
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token不能为空");
                return;
            }

            if (!JWTUtil.verifyToken(token)) {
                logger.error("Token不正确或无效");
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token不正确或无效");
                return;
            }

            Long userId = JWTUtil.getUserIdFromToken(token).orElse(null);
            if (userId == null) {
                logger.error("获取用户ID失败");
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token无效");
                return;
            }

            String redisToken = RedisUtil.getTokenByUserId(userId.toString());
            if (redisToken == null) {
                logger.error("Redis中未找到token");
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未授权访问");
                return;
            }

            if (!token.equals(redisToken)) {
                logger.error("Token与Redis中存储的token不一致");
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token无效");
                return;
            }

            RedisUtil.refreshToken(userId.toString());
            JWTUtil.setUserId(userId);
            chain.doFilter(request, response);
        } catch (Exception e) {
            logger.error("系统异常", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "系统异常");
        } finally {
            JWTUtil.clear();
        }
    }

    // 判断URI是否在白名单中
    private boolean isExcluded(String uri) {
        String[] excludeUrls = {
                "/v3/api-docs",
                "/v3/api-docs/**",
                "/swagger-ui/**",
                "/swagger-ui/index.html",
                "/favicon.ico",
                "/SyUser/login"
        };
        for (String url : excludeUrls) {
            if (url.endsWith("**")) {
                if (uri.startsWith(url.substring(0, url.length() - 2))) {
                    return true;
                }
            } else {
                if (uri.equals(url) || uri.startsWith(url + "/")) {
                    return true;
                }
            }
        }
        return false;
    }
}
